package com.haotunet.app.goldtreasure.activity;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haotunet.app.goldtreasure.R;
import com.haotunet.app.goldtreasure.db.DBOpenHelper;
import com.haotunet.app.goldtreasure.model.BaseModel;
import com.haotunet.app.goldtreasure.model.UserInfo;
import com.haotunet.app.goldtreasure.net.ActionUtil;
import com.haotunet.app.goldtreasure.other.Interface.OnPassBackListener;
import com.haotunet.app.goldtreasure.utils.ActivityUtils;
import com.haotunet.app.goldtreasure.utils.Config;
import com.haotunet.app.goldtreasure.utils.ShareStore;
import com.haotunet.app.goldtreasure.utils.Strs;
import com.haotunet.app.goldtreasure.utils.UIHelper;
import com.haotunet.app.goldtreasure.utils.Utils;
import com.haotunet.app.goldtreasure.views.TitleView;

import cn.tongdun.android.shell.FMAgent;

public class ResetPwdActivity extends BaseActivity {
    private TitleView mTitleView;
    private LinearLayout oldPwdLayout;
    private EditText etOldPwd, etNewPwd, etNewPwdAgain;
    private TextView tvForgetPwd;
    private Button btnLoginAgain;
    private String phone;
    private String code;
    private ActionUtil actionUtil;
    private int type;//type==1 设置登录密码;type==2 修改登录密码;type==3 修改交易密码;type==4,5,6设置交易密码
    private ShareStore shareStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reset_pwd);
        shareStore = new ShareStore(this);
        initView();
    }

    private void initView() {
        actionUtil = new ActionUtil(ResetPwdActivity.this);
        type = getIntent().getIntExtra("type", 0);
        if (type == 1) {
            phone = getIntent().getStringExtra("phone");
        }
        if (type == 1 || type == 4 || type == 6) {
            code = getIntent().getStringExtra("code");
        }
        mTitleView = (TitleView) findViewById(R.id.title_view);
        if (type == 1) {
            mTitleView.getTitletextView().setText(getString(R.string.set_login_pwd));
        } else if (type == 2) {
            mTitleView.getTitletextView().setText(getString(R.string.change_login_pwd));
        } else if (type == 3) {
            mTitleView.getTitletextView().setText(getString(R.string.change_trade_pwd));
        } else if (type == 4 || type == 5 || type == 6) {
            mTitleView.getTitletextView().setText(getString(R.string.set_trade_pwd));
        }
        mTitleView.getTitletextView().setVisibility(View.VISIBLE);

        mTitleView.getBackView().setVisibility(View.VISIBLE);
        mTitleView.getBackView().setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (type == 3) {
                    if (ForgetTradePwdAct.instance != null) {
                        ForgetTradePwdAct.instance.finish();
                    }
                }
                finish();
            }
        });
        oldPwdLayout = (LinearLayout) findViewById(R.id.old_pwd_layout);
        if (type == 2 || type == 3) {
            oldPwdLayout.setVisibility(View.VISIBLE);
            etOldPwd = (EditText) findViewById(R.id.et_old_pwd);
        }
        etNewPwd = (EditText) findViewById(R.id.et_pwd);
        etNewPwdAgain = (EditText) findViewById(R.id.et_pwd_again);
        if (type == 3 || type == 4 || type == 5 || type == 6) {
            etNewPwd.setHint("请输入6位数字密码");
            etNewPwd.setInputType(InputType.TYPE_CLASS_NUMBER);
            etNewPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            etNewPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            etNewPwdAgain.setInputType(InputType.TYPE_CLASS_NUMBER);
            etNewPwdAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
            etNewPwdAgain.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            tvForgetPwd = (TextView) findViewById(R.id.forget_pwd);
        }
        if (type == 3) {
            etOldPwd.setInputType(InputType.TYPE_CLASS_NUMBER);
            etOldPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            etOldPwd.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6)});
            tvForgetPwd.setVisibility(View.VISIBLE);
            tvForgetPwd.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    ActivityUtils.gotoForgetTradePwd(ResetPwdActivity.this, 4);
                    overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                }

            });
        }

        btnLoginAgain = (Button) findViewById(R.id.btn_login_again);
        btnLoginAgain.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String oldPwd = null;
                if (type == 2 || type == 3) {
                    oldPwd = etOldPwd.getText().toString().trim();
                }
                String newPwd = etNewPwd.getText().toString().trim();
                String newPwdAgain = etNewPwdAgain.getText().toString().trim();
                if (type == 2 || type == 3) {
                    if (TextUtils.isEmpty(oldPwd)) {
                        UIHelper.showToast(ResetPwdActivity.this, "请输入原密码!");
                        return;
                    }
                }
                if (TextUtils.isEmpty(newPwd)) {
                    UIHelper.showToast(ResetPwdActivity.this, "请输入密码!");
                    return;
                }
                if (TextUtils.isEmpty(newPwdAgain)) {
                    UIHelper.showToast(ResetPwdActivity.this, "请确认密码!");
                    return;
                }
                if (!newPwd.equals(newPwdAgain)) {
                    UIHelper.showToast(ResetPwdActivity.this, getString(R.string.password_check_up_fail));
                    return;
                }
                if (type == 1 || type == 2) {
                    if (newPwd.length() < Strs.MINLENGTH || newPwd.length() > Strs.MAXLENGTH
                            || !Utils.isPassword(newPwd)) {
                        UIHelper.showToast(ResetPwdActivity.this,
                                getString(R.string.password_format_promat));
                        return;
                    }
                }
                resetPwd(phone, code, oldPwd, newPwd);
            }

            private void resetPwd(String phone, String code, String oldPwd, String newPwd) {
                String imei = Config.getImei(ResetPwdActivity.this);
                String clientId = Config.getUmengToken(ResetPwdActivity.this);
                String blackBox = null;
                if (type == 1) {
                    blackBox = FMAgent.onEvent(ResetPwdActivity.this);
                }
                actionUtil.resetNewPwd(blackBox, type, phone, code, oldPwd, newPwd, imei, clientId);
                actionUtil.setOnPassBackListener(new OnPassBackListener() {

                    @Override
                    public void passBack(BaseModel model) {
                        if (isFinishing()){
                            return;
                        }
                        UserInfo info = (UserInfo) model;
                        if (info == null) {
                            UIHelper.showToast(ResetPwdActivity.this, getString(R.string.rank_fail));
                            return;
                        }
                        if (info.getErrorMsg() != null) {
                            UIHelper.showToast(ResetPwdActivity.this, info.getErrorMsg());
                        } else {
                            if (type == 1) {
                                storeUserInfo(info);
                            }
                            if (type == 5) {
                                shareStore.putInt(Strs.IS_HAD_TRADING_PWD, 1);
                                shareStore.commit();
                            }
                            setResult(RESULT_OK);
                            if (type == 1) {
                                ActivityUtils.skipToMain(ResetPwdActivity.this, "resetPwd");
                            } else if (type == 6) {
                                ResetPwdActivity.this.finish();
                            } else {
                                gotoSettingPwd();
                                UIHelper.showToast(ResetPwdActivity.this, info.getInfo());
                            }
                        }
                    }
                });
            }
        });
    }

    private void storeUserInfo(UserInfo info) {
        shareStore.putBoolean(Strs.IS_LOGIN, true);
        shareStore.putInt(Strs.IS_HAD_TRADING_PWD, info.getIsHadTradingPassword());
        shareStore.putInt(Strs.IS_HAD_BANK_CARD, info.getIsHadBankCard());
        shareStore.commit();
        DBOpenHelper helper = new DBOpenHelper(ResetPwdActivity.this);
        SQLiteDatabase db = helper.getReadableDatabase();
        String mobile = info.getUserName();
        String sql = "select * from HJB_USER where mobile = " + "'" + mobile + "'";
        Cursor rawQuery = db.rawQuery(sql, null);
        if (rawQuery.getCount() != 0) {
            helper.updateUser(mobile, "0", info);
        } else {
            helper.insertUser("0", info);
        }
    }

    private void gotoSettingPwd() {
        Intent intent = new Intent();
        intent.setClass(ResetPwdActivity.this, SettingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (type == 3) {
            if (ForgetTradePwdAct.instance != null) {
                ForgetTradePwdAct.instance.finish();
            }
        }
        return super.onKeyDown(keyCode, event);
    }
}
